﻿using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel;
using Alipay.EasySDK.Kernel.Util;
using Alipay.EasySDK.Payment.FaceToFace.Models;
using Alipay.EasySDK.Payment.Page.Models;
using LiveShopvnext.Order;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace LiveShopvnext.Pay
{
    public class ALiPayAppService : ApplicationService, IALiPayAppService
    {
        private readonly IHttpContextAccessor _contextAccessor;
        private readonly IRepository<Order.OrderInfo, int> _orderInfo;

        public ALiPayAppService(IHttpContextAccessor contextAccessor, IRepository<Order.OrderInfo, int> orderInfo)
        {
            _contextAccessor = contextAccessor;
            _orderInfo= orderInfo;
        }
        [HttpGet]
        //直接测试用地址,记得改订单信息. https://localhost:44341/api/app/a-li-pay/pay?Subject=test1&outTradeNo=111111111112&totalAmount=500
        public async void Pay(PayDto dto)
        {
            _contextAccessor.HttpContext.Response.Cookies.Append("orderInfoWaybillNum",dto.outTradeNo);

            #region 1. 设置参数（全局只需设置一次）
            var config = new Config()
            {
                Protocol = "https",
                GatewayHost = "openapi.alipaydev.com",//"openapi.alipay.com",沙箱
                SignType = "RSA2",
                AppId = "2021000118634798",
                //2021000118634798
                //请填写您的应用私钥
                MerchantPrivateKey = "MIIEowIBAAKCAQEAqb1A/TYXsgOCunP153lt66YLmQRFglYT4FHOGYojOLrwJQkPmKWL55xc8Eo/k26WmKdjihcTqOTXH9M+zIm1IftHBrPzSZQNSmUGJnv5zUx2OE/NxaJF6mUKg5GjwbYsZqR9lsa/qpV401xY8WsS5VIuHulTE68Eer6ISNamfXhiFT7sWcVe2Pzwr8/SqtULitRnMSbw22TrmKmrDZpkF+nha7oyTxSdlZH4kkp4DKVmc0wluLVUly2brKpEtx0AhxOVAllBFaUnkhtUSUHnMtShpPVmytRM6ay3frdpGf0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pmwYT5v397psQKBgGJ5Ot7CAEOw6GlNkkSpjI2VrgyhgQz8VdSQjOaIzp6K3WNx3+h3mN6InFDh8CkR2lLnpi8Hu9UUQ9kRWQNzRQiYL2KVMVLGaGNWt8HJOHi7fSJmtfuBwz6OsEF4YiQfUS2qZL9JdPXTb6qv1tOWOI/dR7oje/FbyFDqnWi1K1r4",
                //支付宝公钥
                AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjnovJ0zKZ//dUh0k1j7J29CdNNAvr+OdiFw85DYCw+MWOCzVauBJqU+vn/fzZRFXCdNSkzDpwQZaTkjfNacb3bKabx3/bjuENRcKWlK1BOHTH4XTsPR3m2TYA7V+txlWiuFZUOa2NgBTD/75zlPaKf0Mxwk9mo2loIdtyH1TS6Jq3ntX7HqvslFluqpK0h7arDG3Z0O6xAPMV47QfGK8pPgO5Kqwt5c4k8VWJv2KhXDYmAu2zHcCDvOGoBAq9SttBi+HONgf+xVlzmL6iIsbbEcVjNLSFAr3McxQ30fG4Vh4xGW9MUMxpZE95bruHW/edRL3kisH9iAr4kfWBlLUtwIDAQABMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjnovJ0zKZ//dUh0k1j7J29CdNNAvr+OdiFw85DYCw+MWOCzVauBJqU+vn/fzZRFXCdNSkzDpwQZaTkjfNacb3bKabx3/bjuENRcKWlK1BOHTH4XTsPR3m2TYA7V+txlWiuFZUOa2NgBTD/75zlPaKf0Mxwk9mo2loIdtyH1TS6Jq3ntX7HqvslFluqpK0h7arDG3Z0O6xAPMV47QfGK8pPgO5Kqwt5c4k8VWJv2KhXDYmAu2zHcCDvOGoBAq9SttBi+HONgf+xVlzmL6iIsbbEcVjNLSFAr3McxQ30fG4Vh4xGW9MUMxpZE95bruHW/edRL3kisH9iAr4kfWBlLUtwIDAQAB"
                //异步回调地址
                //NotifyUrl = "https://localhost:44341/api/app/a-li-pay/notify-url",
            };
            Factory.SetOptions(config);
            #endregion
            try
            {
                // 2. 发起API调用（以创建当面付收款二维码为例）
                //TODO:实训标题和订单号及金额是从dto中取得
                AlipayTradePagePayResponse response = Factory.Payment.Page().Pay(dto.Subject, dto.outTradeNo, dto.totalAmount, "https://localhost:44341/api/app/a-li-pay/return-url");
                // 3. 处理响应或异常
                if (ResponseChecker.Success(response))
                {
                    //把返回的html直接变成网页显示
                    var data = Encoding.UTF8.GetBytes(response.Body);
                    _contextAccessor.HttpContext.Response.ContentType = "text/html";
                    await _contextAccessor.HttpContext.Response.Body.WriteAsync(data, 0, data.Length);
                }
                else
                {
                    Console.WriteLine("调用失败，原因：" + response.Body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("调用遭遇异常，原因：" + ex.Message);


            }
        }
        [HttpGet]
        public string ReturnUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //if()先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update


                return "success";
            }
            return "";
        }
        [HttpGet]
        public string NotifyUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update
                //再循环返回库存
                //update
                _contextAccessor.HttpContext.Request.Cookies.TryGetValue("orderInfoWaybillNum", out string orderInfoWaybillNum);

                var orderInfo = _orderInfo.FirstOrDefault(x => x.orderInfoWaybillNum == orderInfoWaybillNum);

                if (orderInfo.orderInfoState != (int)CommunalEnum.OrderType.Shipped) //使用枚举
                {
                    orderInfo.orderInfoState = (int)CommunalEnum.OrderType.Shipped; //使用枚举
                    _orderInfo.UpdateAsync(orderInfo);
                    _contextAccessor.HttpContext.Response.Cookies.Delete("orderInfoWaybillNum");
                    return "success";
                }
                else
                { 
                    return "success";
                }
                

                
            }
            return "";
        }
    }
}
